from ph_utils.common import is_blank

# 全局状态码错误信息表
GLOBAL_CODE_ERRORS = {
    0: "SUCCESS",
    400001: "缺少 app_id 请求或者 app_id 错误",
    400002: "请求参数 timestamp 错误",
    400003: "参数错误",
    400005: "IP 没有添加白名单, 需用用户配置服务器白名单ip",
    400008: "签名错误",
    400004: "HTTP请求错误",
    400029: "API 调用太频繁，请稍候再试",
    400030: "用户受限, 可能是没有申请",
    500000: "系统异常",
}

# 随机数基础字符串
RANDOM_BASE = "QWERTYUIOPLKJHGFDSAZXCVBNMqwertyuioplkjhgfdsazxcvbnm0987654321"


def jsonify(data=None, code=0, message=None, page_info=None, extra=None):
    """返回通用格式的数据, code, message, data

    Args:
        data (object|list): 返回的数据
        code (int): 状态码
        message (str): 响应信息
        page_info (dict): 返回分页信息
        extra (dict): 额外返回的其它信息

    Returns:
        Response: sanic json response
    """
    if code in GLOBAL_CODE_ERRORS and message is None:
        message = GLOBAL_CODE_ERRORS[code]
    r = {"code": code, "message": message, "data": data}
    if data is not None:
        r["data"] = data
    if page_info is not None:
        r["pageInfo"] = page_info
    if extra is not None:
        r["extra"] = extra
    return r


def remote_info(request):
    """获取登录的设备信息

    Args:
        request (request): 请求

    Returns:
        dict: ip - 登录ip, userAgent - 浏览器的 user-agent
    """
    remote_addr = request.remote_addr  # 登录ip
    if is_blank(remote_addr):
        remote_addr = "127.0.0.1"
    headers = request.headers
    user_agent = headers.get("user-agent")  # 登录设备的 user_agent
    if is_blank(user_agent):
        user_agent = headers.get("sec-ch-ua")
    return {"ip": remote_addr, "userAgent": user_agent}
